import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import * as echarts from 'echarts';

/* 自定义服务 */
import { GetEchartDataService } from '../../services/get-echart-data.service';

declare var $: any;  // 使用JQuery时加上，目的是不让编译时报错

@Component({
  selector: 'app-echart02',
  templateUrl: './echart02.component.html',
  styleUrls: ['./echart02.component.css']
})
export class Echart02Component implements OnInit {

  public option1 = {
    title: {
      text: '异步数据加载示例1'
    },
    tooltip: {},
    legend: {
      data: ['销量']
    },
    xAxis: {
      data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
    },
    yAxis: {},
    series: [{
      name: '销量',
      type: 'bar',
      data: [5, 20, 36, 10, 10, 20]
    }]
  };
  public option2 = {
    title: {
      text: '异步数据加载示例2'
    },
    tooltip: {},
    legend: {
      data: ['销量']
    },
    xAxis: {
      data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
    },
    yAxis: {},
    series: [{
      name: '销量',
      type: 'bar',
      data: [5, 20, 36, 10, 10, 20]
    }]
  };
  private echart1;
  private echart2;

  constructor(private router: Router,private getEchartDataService: GetEchartDataService) { }

  ngOnInit() {
    this.drawEchart1();
    this.drawEchart2();

    setTimeout(() => { this.updateOption1() }, 1000);
    setTimeout(() => { this.updateOption2() }, 2000);
  }

  drawEchart1() {
    this.echart1 = echarts.init(document.getElementById('e1'));
    this.echart1.setOption(this.option1);
  }

  /** 直接读取本地文件 */
  updateOption1() {
    this.echart1.showLoading();
    let that = this;
    // JSON文件已经在angular-cli.json中配置到了assets中，可以访问
    $.get('../modules/mockdata/data.json').done(function (res) {
      that.echart1.hideLoading();
      that.echart1.setOption({
        title: {
          text: '异步数据加载示例1'
        },
        tooltip: {},
        legend: {
          data: ['销量']
        },
        xAxis: {
          data: res.categories
        },
        yAxis: {},
        series: [{
          name: '销量',
          type: 'bar',
          data: res.data
        }]
      });
    });
  }

  drawEchart2() {
    this.echart2 = echarts.init(document.getElementById('e2'));
    this.echart2.setOption(this.option2);
  }

  /** 从服务获取数据 */
  updateOption2() {
    this.echart2.showLoading();
    let that = this;
    // 对于返回的Observable，使用.subscribe，若为Promise，使用.then
    this.getEchartDataService.getData().subscribe(res => {
      let data = res.data;
      if(res.ret == 'ok'){
        that.echart2.hideLoading();
        that.echart2.setOption({
          title: {
            text: '异步数据加载示例2'
          },
          tooltip: {},
          legend: {
            data: ['销量']
          },
          xAxis: {
            data: data.categories
          },
          yAxis: {},
          series: [{
            name: '销量',
            type: 'bar',
            data: data.data
          }]
        });
      }
    });
  }
}
